

/* =======  单元格的数字存储  扩展一些处理数组的方法 开始 =========== */

//单元格可以出现的数据

// 整数数组
var integerArr = (function () {
    var arr = [];
    for (var i = -9; i <= 9; i++) {
        arr.push(i);
    }
    return arr;
})();
// console.log(integerArr);

// 系数组
var coefficientArr = (function () {
    var arr = [];
    for (var i = -5; i <= 5; i++) {
        if (i !== 0) {
            arr.push(i);
        }
    }
    return arr;
})();
// console.log(coefficientArr);

//单元格中所有可出现的数系
var arr1 = [
    [1, 2], [1, 1, 2], [1, 3], [1, 1, 3],
    [1, 2, 3], [1, 4], [1, 1, 4], [1, 3, 4],
    [1, 5], [1, 1, 5], [1, 2, 5], [1, 3, 5],
    [1, 4, 5]
];
// 与+1/2，-1/2凑整的数
var arr2 = [
    [1, 2], [1, 1, 2]
];

// 与1/3，2/3凑整的数
var arr3 = [
    [1, 3], [2, 3], [1, 1, 3], [1, 2, 3]
];


// 与1/4，3/4凑整的数
var arr4 = [
    [1, 4], [3, 4], [1, 1, 4], [1, 3, 4]
];


// 与1/5，4/5凑整的数
var arr5 = [
    [1, 5], [4, 5], [1, 1, 5], [1, 4, 5]
];

// 与2/5，3/5凑整的数
var arr5_1 = [
    [2, 5], [3, 5], [1, 2, 5], [1, 3, 5]
];

// 与1/6-5/6凑整的数
var arr6 = [
    [1, 6], [5, 6], [1, 1, 6], [1, 5, 6]
];

//去除clickedCellArr数组中的重复项
Array.prototype.unique = function () {
    var newArr = [this[0]];
    for (var i = 0; i < this.length; i++) {
        if (this[i].dataNum !== newArr[newArr.length - 1].dataNum) {
            newArr.push(this[i]);
        }
    }
    return newArr;
};


//从一个数组中随机获取n个数组元素
Array.prototype.getRandomArrayElements = function (count) {
    var shuffled = this.slice(0), i = this.length, min = i - count, temp, index;
    while (i-- > min) {
        index = Math.floor((i + 1) * Math.random());
        temp = shuffled[index];
        shuffled[index] = shuffled[i];
        shuffled[i] = temp;
    }
    return shuffled.slice(min);
};
// console.log( cellsArray.getRandomArrayElements(6) );
// console.log( arr3.getNegative().getRandomArrayElements(1));

// 从数组元素的索引中随机选取n个索引
Array.prototype.getRandomIndexArr = function (count) {
    var arrIndexArr = [];
    var indexArr;
    for (var i = 0; i < this.length; i++) {
        arrIndexArr.push(i);
    }
    indexArr = arrIndexArr.getRandomArrayElements(count);
    // console.log(indexArr);
    return indexArr;
};

//从整数数组中随机选取n个数组元素，
// 并满足条件：正数和负数的个数相差2个及以内时，随机出现，相差超过两个，则只出现少的那种

Array.prototype.getRandomIntegerFromArr = function (count, flag) {
    var cellsMsgArr = [];
    var txtHtmlArr = [];
    var randomNumArr = this.getRandomArrayElements(count);
    for (var i = 0; i < randomNumArr.length; i++) {
        if (flag) {
            // console.log("flag:" + flag);
            if (flag > 2) {
                xishu = getRandomNum(-9, -1);
                // console.log("正数多" + xishu);
            } else if (flag < -2) {
                xishu = getRandomNum(1, 9);
                // console.log("负数多" + xishu);
            } else {
                xishu = getRandomNum(-9, 9);
            }
        } else {
            xishu = getRandomNum(-9, 9);
        }
        var randomNum = xishu * 1;
        txtHtmlArr.push(randomNum);
        cellsMsgArr.push({"xishu": xishu, "arrItem": randomNum, "dataResult": randomNum});
    }

    // console.log(indexArr,count);

    return {
        txtHtmlArr: txtHtmlArr,
        cellsMsgArr: cellsMsgArr
    };
};


// 根据选取的随机索引找到对应的随机分数，并随机获取二个整数

Array.prototype.getRandomNumFromArr = function (count,flag) {
    // console.log("count:" + count);
    var cellsMsgArr = [];
    var txtHtmlArr = [];
    var colorArr = ['#64E9FF','#F1F5A2','#66FF8D','#EC9CF0'];
    var txtHtml_1, txtHtml_2, txtHtml_3, txtHtml_4;
    var arrItem;
    var fenzi, fenmu, indexArrLength;
    var xishu;
    for (var i = 0; i < count; i++) {
        // console.log("flag:" + flag);
        if(i < count -1){
            if (flag > 2) {
                xishu = getRandomNum(-9, -1);
                // console.log("正数多" + xishu);
            } else if (flag < -2) {
                xishu = getRandomNum(1, 9);
                // console.log("负数多" + xishu);
            } else {
                xishu = getRandomNum(-9, 9);
            }
            var randomNum = xishu * 1;
            txtHtmlArr.push(randomNum);
            cellsMsgArr.push({"xishu": xishu, "arrItem": randomNum, "dataResult": randomNum});
        }else{
            var indexArr = this.getRandomIndexArr(1);
            indexArrLength = this[indexArr[0]].length;
            if (indexArrLength === 2) {
                fenzi = this[indexArr[0]][0];
                fenmu = this[indexArr[0]][1];
                xishu = [-1, 1].getRandomArrayElements(1)[0];
                txtHtml_1 = "<div class='fraction minus' style='color:"+ colorArr[fenmu-2]+"';>" +
                    "<span class='xishu'>-</span>" +
                    "<span class='fenzi'>" + fenzi + "</span><i class='fenshuxian' style='background-color:"+ colorArr[fenmu-2]+"';></i>" +
                    "<span class='fenmu'>" + fenmu + "</span>" +
                    "</div>";
                txtHtml_2 = "<div class='fraction plus' style='color:"+ colorArr[fenmu-2]+"';>" +
                    "<span class='fenzi'>" + fenzi + "</span><i class='fenshuxian' style='background-color:"+ colorArr[fenmu-2]+"';></i>" +
                    "<span class='fenmu'>" + fenmu + "</span>" +
                    "</div>";
                if (xishu < 0) {
                    txtHtmlArr.push(txtHtml_1);
                } else {
                    txtHtmlArr.push(txtHtml_2);
                }
                arrItem = xishu * fenzi / fenmu;
                cellsMsgArr.push({"xishu": xishu, "arrItem": this[indexArr[0]], "dataResult": arrItem});
                // console.log("系数：" + xishuArr[0], "元素：" + arr[indexArr[i]], "数据：" + arrItem);
            }
            else if (indexArrLength === 3) {
                fenzi = this[indexArr[0]][1];
                fenmu = this[indexArr[0]][2];
                xishu = coefficientArr.getRandomArrayElements(1)[0];
                txtHtml_3 = "<div class='mixedNumber minus' style='color:"+ colorArr[fenmu-2]+"';>" +
                    "<span class='xishu'>" + xishu * this[indexArr[0]][0] + "</span>" +
                    "<span class='fenzi'>" + fenzi + "</span><i class='fenshuxian' style='background-color:"+ colorArr[fenmu-2]+"';></i>" +
                    "<span class='fenmu'>" + fenmu + "</span>" +
                    "</div>";

                txtHtml_4 = "<div class='mixedNumber plus' style='color:"+ colorArr[fenmu-2]+"';>" +
                    "<span class='xishu'>" + xishu * this[indexArr[0]][0] + "</span>" +
                    "<span class='fenzi'>" + fenzi + "</span><i class='fenshuxian' style='background-color:"+ colorArr[fenmu-2]+"';></i>" +
                    "<span class='fenmu'>" + fenmu + "</span>" +
                    "</div>";
                if (xishu < 0) {
                    txtHtmlArr.push(txtHtml_3);
                    arrItem = xishu * this[indexArr[0]][0] - fenzi / fenmu;

                } else {
                    txtHtmlArr.push(txtHtml_4);
                    arrItem = xishu * this[indexArr[0]][0] + fenzi / fenmu;
                }

                cellsMsgArr.push({"xishu": xishu, "arrItem": this[indexArr[0]], "dataResult": arrItem});
                // console.log("系数：" + xishuArr[0], "元素：" + arr[indexArr[i]], "数据：" + arrItem);
            }
        }
    }

    // console.log(cellsMsgArr);
    return {
        txtHtmlArr: txtHtmlArr,
        cellsMsgArr: cellsMsgArr
    };
};


/* =======  单元格的数字存储  扩展一些处理数组的方法 结束=========== */


// 给每一个单元格定位，设置私有属性并将属性值存储在 cellsArray 数组中
var cellSideWidth = 0.98;
var cellSideHeight = 0.98;
var cellTopSpace = 0.1795;
var cellLeftSpace = 0.1935;

function setTableAttr(rowNum, columnNum, cellsArray) {
    var dataNum = "";
    cellsArray = cellsArray || [];
    for (var i = 0, len1 = rowNum; i < len1; i++) {
        dataNum += i;
        // console.log(i);
        for (var j = 0, len2 = columnNum; j < len2; j++) {
            dataNum += j;
            cellsArray.push(dataNum);

            $("#grid-cell-" + i + "-" + j).attr({
                "data-num": dataNum,
                "style": "top: " + getPosTop(i, j) + ";left:" + getPosLeft(i, j)
            });
            dataNum = dataNum.slice(0, 1);
            // console.log(j);
            if (j == len2 - 1) {
                dataNum = "";
            }

        }
    }
    return cellsArray;
}
// console.log(cellsArray);

// 给每个单元格定位
function getPosTop(i, j) {
    return 0.069 + i * ( cellTopSpace + cellSideHeight ) + "rem";
}

function getPosLeft(i, j) {
    return 0.069 + j * ( cellLeftSpace + cellSideWidth ) + "rem";
}

// 随机设置小怪兽
function setMonster() {
    var monsterMsg = {};
    var canvasIndex = getRandomNum(0, 5);
    var contrastData = getRandomNum(-9, 9);
    // console.log(contrastData);
    $(".monster>canvas").eq(canvasIndex).show().siblings("canvas").hide();
    var animaIndex = animaCreateJs.prototype.getIndexById("canvas" + (canvasIndex + 1));
    var animaObj = animaCreateJs.prototype.animationArr[animaIndex];
    var anima = animaObj["anima"];
    var currentFrame = 0;
    anima.gotoAndPlay(0);
    anima.addEventListener("tick", animaControllerPlaying);
    function animaControllerPlaying() {
        currentFrame++;
        if (currentFrame == 30) {
            $(".contrastData").html(contrastData);
            anima.removeEventListener("tick", animaControllerPlaying);
        }
    }

    monsterMsg.contrastData = contrastData;
    monsterMsg.canvasIndex = canvasIndex;
    return monsterMsg;
}

// 获取某一范围内的随机数
function getRandomNum(Min, Max) {
    var Range = Max - Min;
    var Rand = Math.random();
    return (Min + Math.round(Rand * Range));
}

// 随机选取n个空单元格设置其内容为选择好的随机数
var callNumber = 0; // 统计getRandomNumFromArr方法的调用次数
function setCellsAbleArr(cellsArray, score, count, flag) {
    // console.log(filledCellsMsgArr);
    var cellsMsgObj = {};
    if (count === 6) {
        $(".grid-container>.grids").children(".grid-cell").html("");
    }
    var textContentArr = [];
    var cellsMsgArr = [];
    var cellsAbleArr = (function (arr) {
        var cellsAbleArr = [];
        for (var i = 0, len = arr.length; i < len; i++) {
            var index = arr[i];
            var row = index.slice(0, 1);
            var column = index.slice(1);
            if (!$("#grid-cell-" + row + "-" + column).html()) {
                cellsAbleArr.push(index);
            }
        }
        return cellsAbleArr;
    })(cellsArray);
    if (cellsAbleArr.length === 30) {
        count = 6;
    }
    else if (cellsAbleArr.length === 1) {
        count = 1;
    }
    else if (cellsAbleArr.length === 2){
        count = 2;
    }
    else{
        count = 3;
    }

    if (cellsAbleArr.length > 0) {
        var cellsIndexArr = cellsAbleArr.getRandomIndexArr(count);
        // console.log("cellsIndexArrLength:"+ cellsIndexArr.length);
        var randomNumFromArr;
        if (score < 3000) {
            randomNumFromArr = integerArr.getRandomIntegerFromArr(count, flag);
            textContentArr = randomNumFromArr.txtHtmlArr;
            cellsMsgArr = randomNumFromArr.cellsMsgArr;
        } else if(score >= 3000 && score < 5000){
            callNumber++;
            if(callNumber <= 2){
                randomNumFromArr = integerArr.getRandomIntegerFromArr(count, flag);
                textContentArr = randomNumFromArr.txtHtmlArr;
                cellsMsgArr = randomNumFromArr.cellsMsgArr;
            }else{
                randomNumFromArr = arr1.getRandomNumFromArr(count,flag);
                textContentArr = randomNumFromArr.txtHtmlArr;
                cellsMsgArr = randomNumFromArr.cellsMsgArr;
                callNumber = 0;
            }
        } else{
            randomNumFromArr = arr1.getRandomNumFromArr(count,flag);
            textContentArr = randomNumFromArr.txtHtmlArr;
            cellsMsgArr = randomNumFromArr.cellsMsgArr;
        }

        // console.log(randomNumFromArr);
        // console.log(textContentArr);
        var index, row, column;

        for (var i = 0, len = cellsIndexArr.length; i < len; i++) {
            index = cellsAbleArr[cellsIndexArr[i]];
            cellsMsgArr[i]["cellIndex"] = index;
            // console.log(cellsMsgArr[i].dataResult);
            // console.log(typeof index);
            row = index.slice(0, 1);
            column = index.slice(1);
            if (count == 1) {
                $("#grid-cell-" + row + "-" + column).html(textContentArr[textContentArr.getRandomIndexArr(1)[0]]);
            } else if(count == 2){
                var textHtmlIndexArr = textContentArr.getRandomIndexArr(2);
                // console.log(textHtmlIndexArr);
                for(var j = 0,lenj= textHtmlIndexArr.length; j<lenj; j++){
                    // console.log(textContentArr[textHtmlIndexArr[j]]);
                    $("#grid-cell-" + row + "-" + column).html(textContentArr[textHtmlIndexArr[j]]);
                }
            } else {
                $("#grid-cell-" + row + "-" + column).html(textContentArr[i]);
            }

        }
    }

    // console.log(cellsMsgArr);

    cellsMsgObj.cellsMsgArr = cellsMsgArr;
    cellsMsgObj.cellsAbleArr = cellsAbleArr;
    return cellsMsgObj;
}


//加载电流连线动画
var canvas = document.getElementById("canvas17");
var stage = new createjs.Stage(canvas);
function initLineAnima(arr, timer, loadElectricAnima) {
    var exportRoot = [], currentFrame = 0, totalFrames = 30;

    images = images || {};
    ss = ss || {};

    var loader = new createjs.LoadQueue(false);
    loader.addEventListener("fileload", function (evt) {
        if (evt.item.type == "image") {
            images[evt.item.id] = evt.result;
        }
    });
    loader.addEventListener("complete", function (evt) {
        var queue = evt.target;
        ss["line_atlas_"] = queue.getResult("line_atlas_");

        arr.forEach(function (item, index) {
            exportRoot[index] = new line.line();
            exportRoot[index].setTransform(item.left, item.top, item.scaleX, 1, item.angle);
            stage.addChild(exportRoot[index]);
        });
        $(canvas).show();
        // console.log(timer);
        clearInterval(timer);
        stage.update();

        createjs.Ticker.setFPS(line.properties.fps);
        createjs.Ticker.addEventListener("tick", stage);
        createjs.Ticker.addEventListener("tick", tickHandler);
    });
    loader.loadFile({src: "images/line_atlas_.json", type: "spritesheet", id: "line_atlas_"}, true);
    loader.loadManifest(line.properties.manifest);

    function tickHandler() {
        currentFrame++;
        if (currentFrame == totalFrames) {
            $(canvas).hide();
            // console.log("销毁");
            // console.log(stage.numChildren);
            stage.removeAllChildren();
            // console.log(stage.numChildren);
            arr = [];
            loadElectricAnima();
        }
    }
}

